# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import base64
import logging
import os
import re
import time

from django.http import Http404, HttpResponse
from django.utils.encoding import smart_str
from django.views.decorators.csrf import csrf_exempt
from wenlincms.utils.models import get_user_model

from mainsys.settings import MEDIA_ROOT, MEDIA_URL
from wlapps.article.models import ArticlePost, ArticleCategory
from wlapps.utils import xmltodict

"""
文章的xmlrpc发布接口
"""

# 在终端中配置的用户名和密码，请务必同时在管理后台添加此用户
xml_user = "xmlrpc_publisher"
xml_pw = "123456"

User = get_user_model()
add_log = logging.getLogger('error')


@csrf_exempt
def article_xmlrpc(request):
    if request.method == "POST":
        xml_str = smart_str(request.body)
        success_xml = """
                <?xml version="1.0" encoding="UTF-8"?>
                <methodResponse>
                  <params>
                    <param>
                      <value>
                      <string>2</string>
                      </value>
                    </param>
                  </params>
                </methodResponse>
                """
        error_xml = """
                <?xml version="1.0" encoding="UTF-8"?>
                <methodResponse>
                  <fault>
                    <value>
                      <struct>
                        <member>
                          <name>faultCode</name>
                          <value><int>4</int></value>
                        </member>
                        <member>
                          <name>faultString</name>
                          <value><string>系统错误</string></value>
                        </member>
                      </struct>
                    </value>
                  </fault>
                </methodResponse>
                """
        img_prefix = time.strftime('%Y%m%d%H', time.localtime())[2:]
        import traceback
        try:
            user_id = User.objects.filter(username=xml_user)
            user_id = user_id[0].id if len(user_id) else None
            flag = 0
            if user_id:
                request_xml = xmltodict.parse(xml_str)
                username = request_xml['methodCall']['params']['param'][1]['value']['string']
                password = request_xml['methodCall']['params']['param'][2]['value']['string']
                if username == xml_user and password == xml_pw:
                    methodname = request_xml['methodCall']['methodName']

                    # 如果是图片
                    if "Media" in methodname:
                        ztype = request_xml['methodCall']['params']['param'][3]['value']['struct'][
                            'member'][3]['value']['string']
                        if "image" in ztype:
                            bits = request_xml['methodCall']['params']['param'][3]['value']['struct'][
                                'member'][0]['value']['base64']
                            title = request_xml['methodCall']['params']['param'][3]['value']['struct'][
                                'member'][1]['value']['string']
                            img_titles = title.split('_')
                            if len(img_titles) > 1:
                                flag = 1
                                img_title = img_prefix + title.replace(img_titles[0] + '_', '')
                                img_path = os.path.join(MEDIA_ROOT, "xmlrpc/" + img_title)
                                img_bits = base64.b64decode(bits)
                                the_img = open(img_path, 'wb')
                                the_img.write(img_bits)
                                the_img.close()

                    # 新建文章
                    elif "newPost" in methodname:
                        category = request_xml['methodCall']['params']['param'][3]['value']['struct'][
                            'member'][0]['value']['array']['data']['value']['string']
                        the_cat = ArticleCategory.objects.filter(title=category)
                        content = request_xml['methodCall']['params']['param'][3]['value']['struct'][
                            'member'][1]['value']['string'].strip()
                        title = request_xml['methodCall']['params']['param'][3]['value']['struct'][
                            'member'][4]['value']['string'].strip()
                        if title and content:
                            flag = 1
                            the_post = ArticlePost.objects.filter(title=title)
                            # 替换正文中的图片
                            content = subimg(content, img_prefix)
                            if len(the_post):
                                # 编辑已有文章
                                new_zhi = {'content': content}
                                the_post.update(**new_zhi)
                                the_post[0].save()
                            else:
                                # 新建流程
                                new_zhi = {'comments_count': 0, 'user_id': int(user_id), 'audit_status': 1, 'status': 2,
                                           'title': title, 'content': content}
                                new_post = ArticlePost.objects.create(**new_zhi)
                                if len(the_cat):
                                    new_post.categories.add(the_cat[0])
                                new_post.save()

            if flag == 1:
                return HttpResponse(success_xml, content_type='text/xml')
            else:
                return HttpResponse(error_xml, content_type='text/xml')
        except Exception:
            add_log.info("XMLRPC POST ERROR: %s\n%s", xml_str, str(traceback.format_exc()))
            return HttpResponse(error_xml, content_type='text/xml')
    else:
        raise Http404


# 替换正文
def subimg(zw, img_prefix):
    # 替换正文中的图片
    result = re.sub(r'(?P<z1>img\s+src=")(?P<z2>[^/"]+)/(?P<z3>[^"]+)',
                    '\g<z1>' + MEDIA_URL + 'xmlrpc/' + img_prefix + '\g<z3>', zw)
    return result
